package com.tutorial.demo.goods.service;

import com.tutorial.demo.goods.mapper.TbgoodsMapper;
import com.tutorial.demo.goods.pojo.Tbgoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class TbgoodsService {
    @Autowired
    private TbgoodsMapper tbgoodsMapper;


    public List<Tbgoods> findAllByParentId(int parentId){
        return tbgoodsMapper.selectAllByParantId(parentId);
    }
    //查询所有商品
    public List<Tbgoods> findAll(){
        return tbgoodsMapper.selectAll();
    }

    public Tbgoods findById(int id){
        return tbgoodsMapper.selectById(id);
    }

    public List<Tbgoods> query(int id){
        List<Tbgoods> ret = new ArrayList<>();
        Tbgoods tbgoods = findById(id);
        if(tbgoods == null){
            return null;
        }
        ret.add(tbgoods);
        //如果是根目录
        if(tbgoods.getParentId() == 0){
            return ret;
        }
        query(ret,tbgoods.getParentId());
        Collections.sort(ret, new Comparator<Tbgoods>() {
            @Override
            public int compare(Tbgoods o1, Tbgoods o2) {
                if(o1.getId() > o2.getId()){
                    return 1;
                }else if(o1.getId() < o2.getId()){
                    return -1;
                }else {
                    return 0;
                }
            }
        });
        return ret;
    }
    //查询id=#{id}的tbgoods,并把结果放在ret中
    private void query(List<Tbgoods> ret, int id){
        Tbgoods tbgoods = tbgoodsMapper.selectById(id);
        ret.add(tbgoods);
        if(tbgoods.getParentId() == 0){
            return;
        }
        query(ret,tbgoods.getParentId());
    }

}
